import { replaceByObj } from "./xUtil.js";
import xID from "./xID.js";

const tmplRow = '<div class="row" type="row" data-index="{{index}}">{{html}}</div>';
const tmplCol = '<div class="{{col}}" type="col" data-index="{{index}}">{{html}}</div>';
const tmplGrid = '<div class="{{grid}}" type="grid"  id ="{{id}}"> {{html}} </div>';
const tmplGroup = `<div class="row"  type="row"> 
                       <div class="col" type="group"><span>{{group}}</span></div>
                    </div>`;


/*
*  cfg : {data :[{cell}],
*         style: ,
*         col //缺省 col 设置,
*         cbRenderCell : item 渲染 回调函数
*  }
*
*  cell:{ col :  col-xl-9
*
*  }
*
*
* */
export default class xGrid{
	
	static getInstance() {
		if(!this.instance) {
			this.instance = new xGrid();
		}
		return this.instance;
	}
	
	/*
	 根据类判断 rowsize ； 默认 6 ，超过12 就换行
	 *  */
	
    static renderGrid(cfg){
    	let rowSize =0 ;
    	let rowIndex = 0;
    	let colIndex = 0;
    	let colHtmls = '' ;
    	let rowHtmls = '' ;
    	let group ='';

    	for(let i=0;i<cfg.data.length;i++){
    	    if(cfg.group && cfg.data[i].group!=group){
                if(colHtmls){
                    rowHtmls += replaceByObj(tmplRow,{index:rowIndex,html:colHtmls});
                    colHtmls = '';
                }
                rowHtmls  += tmplGroup.replace('{{group}}',cfg.data[i].group);
                group = cfg.data[i].group;
                rowSize = 0 ;
            }
            let col = cfg.data[i].col||cfg.col;
    		colHtmls += xGrid.renderCol(cfg.data[i],cfg.cbRenderCell,i,col);
    		colIndex += 1;

            let colSize = xGrid.getColSize(col);
            rowSize +=colSize-0;
            let nextSize = 0;
            if(i<cfg.data.length-1)
                nextSize = xGrid.getColSize(cfg.data[i+1].col||cfg.col) ;
    		if(rowSize+nextSize >12 || i == cfg.data.length-1){
                rowSize = 0 ;
    			rowIndex +=1;
    			rowHtmls += replaceByObj(tmplRow,{index:rowIndex,html:colHtmls});
    			colHtmls = '';
    		}
    	}
    	return replaceByObj(tmplGrid,{grid:cfg.grid||'',
    	    id:cfg.id||xID.getID(),
    	    html:rowHtmls})
    }

    static getColSize(col){
        if(col &&  /(xl|sm|lg|md)-[0-9]+/.test(col)){
            let tmp = col.match(/(xl|sm|lg|md)-[0-9]+/)[0];
            return tmp?tmp.split('-')[1]-0:4;
        }else
            return 6;
    }

	static renderCol(cell,cbRenderCell,index,col) {
		let html='';
		if(cbRenderCell)
			html = cbRenderCell(cell);
		return replaceByObj(tmplCol, {
			html,
			index,
            col:cell.col||col||''
		});
	}

}